package com.hdsx.jxcsxm.shares.controller;

import com.hdsx.jxcsxm.funds.bean.FundBean;
import com.hdsx.jxcsxm.shares.bean.JhxdwhBean;
import com.hdsx.jxcsxm.shares.bean.ResultBean;
import com.hdsx.jxcsxm.shares.bean.ShareBean;
import com.hdsx.jxcsxm.shares.server.ShareServer;
import com.hdsx.jxcsxm.utile.*;
import com.hdsx.jxcsxm.utile.excel.ExcelCoordinate;
import com.hdsx.jxcsxm.utile.excel.ExcelEntity;
import com.hdsx.jxcsxm.utile.excel.ExcelExportUtil;
import com.hdsx.jxcsxm.utile.excel.ExcelTitleCell;
import com.hdsx.jxcsxm.xtgl.bean.TreeNode;
import com.hdsx.jxcsxm.xtgl.bean.Xmjbxx;
import com.hdsx.jxcsxm.zjdw.bean.XmZjdw;
import com.hdsx.webutil.struts.BaseActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author 占贤银
 * time 2024/2/26 10:18
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
@Scope("prototype")
@Controller
public class ShareController extends BaseActionSupport implements ModelDriven<ShareBean> {

    private ShareBean shareBean = new ShareBean();

    @Resource(name = "shareServerImpl")
    private ShareServer shareServer;

    private File fileupload;
    private String fileuploadFileName;

    public File getFileupload() {
        return fileupload;
    }

    public void setFileupload(File fileupload) {
        this.fileupload = fileupload;
    }

    public String getFileuploadFileName() {
        return fileuploadFileName;
    }

    public void setFileuploadFileName(String fileuploadFileName) {
        this.fileuploadFileName = fileuploadFileName;
    }

    @Override
    public ShareBean getModel() {
        return shareBean;
    }

    public void getdwTj() {
        try {
            JsonUtils.write(shareServer.getdwTj(shareBean), getresponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void queryJhXmlist() {
        shareBean.setXzqh(MyUtil.getQueryTJ(shareBean.getXzqh(), "xzqhdm"));
        shareBean.setXmnf(MyUtil.getQueryTJ(shareBean.getXmnf(), "xmnf"));
        shareBean.setTsdq(MyUtil.getQueryTJ(shareBean.getTsdq(), "tsdq"));
        shareBean.setJhxdwh(MyUtil.getQueryTJIN(shareBean.getJhxdwh(), "jhxdwh"));
        shareBean.setGydwdm(MyUtil.getQueryTJDW(shareBean.getGydwdm(), "gydwdm"));
        List<ShareBean> list=shareServer.queryJhXmlist(shareBean);
        int count=shareServer.queryJhXmlistCount(shareBean);
        EasyUIPage<ShareBean> e=new EasyUIPage<ShareBean>();
        e.setRows(list);
        e.setTotal(count);
        try {
            JsonUtils.write(e, getresponse().getWriter());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void queryXmlist() {
        shareBean.setXzqh(MyUtil.getQueryTJ(shareBean.getXzqh(), "xzqhdm"));
        shareBean.setXmnf(MyUtil.getQueryTJ(shareBean.getXmnf(), "xmnf"));
        shareBean.setTsdq(MyUtil.getQueryTJ(shareBean.getTsdq(), "tsdq"));
        shareBean.setJhxdwh(MyUtil.getQueryTJIN(shareBean.getJhxdwh(), "jhxdwh"));
        shareBean.setGydwdm(MyUtil.getQueryTJDW(shareBean.getGydwdm(), "gydwdm"));
        List<ShareBean> list=shareServer.queryXmlist(shareBean);
        int count=shareServer.queryXmlistCount(shareBean);
        EasyUIPage<ShareBean> e=new EasyUIPage<ShareBean>();
        e.setRows(list);
        e.setTotal(count);
        try {
            JsonUtils.write(e, getresponse().getWriter());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void getJhTjAll() {
        shareBean.setXzqh(MyUtil.getQueryTJ(shareBean.getXzqh(), "xzqhdm"));
        shareBean.setXmnf(MyUtil.getQueryTJ(shareBean.getXmnf(), "xmnf"));
        shareBean.setTsdq(MyUtil.getQueryTJ(shareBean.getTsdq(), "tsdq"));
        shareBean.setJhxdwh(MyUtil.getQueryTJIN(shareBean.getJhxdwh(), "jhxdwh"));
        shareBean.setGydwdm(MyUtil.getQueryTJDW(shareBean.getGydwdm(), "gydwdm"));
        try {
            JsonUtils.write(shareServer.getJhTjAll(shareBean), getresponse().getWriter());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void getTjAll() {
        shareBean.setXzqh(MyUtil.getQueryTJ(shareBean.getXzqh(), "xzqhdm"));
        shareBean.setXmnf(MyUtil.getQueryTJ(shareBean.getXmnf(), "xmnf"));
        shareBean.setTsdq(MyUtil.getQueryTJ(shareBean.getTsdq(), "tsdq"));
        shareBean.setJhxdwh(MyUtil.getQueryTJIN(shareBean.getJhxdwh(), "jhxdwh"));
        shareBean.setGydwdm(MyUtil.getQueryTJDW(shareBean.getGydwdm(), "gydwdm"));
        try {
            JsonUtils.write(shareServer.getTjAll(shareBean), getresponse().getWriter());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void getSharejhxdwh() {
        try {
            JsonUtils.write(shareServer.getSharejhxdwh(shareBean), getresponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getbfTj(){
        try {
            JsonUtils.write(shareServer.getbfTj(shareBean), getresponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getShareTreeByName() {
        try {
            shareBean.setXmbm(URLDecoder.decode(shareBean.getXmbm(), "utf-8"));
            List<JhxdwhBean> list =  shareServer.getWhTreeByNameShNew(shareBean);
            JsonUtils.write(list, getresponse().getWriter());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insertOrUpdateShqx() {
        try {
            String[] gydwdm = shareBean.getGydwdm().split(",");
            String[] gydw = shareBean.getGydw().split(",");
            String[] parent = shareBean.getParent().split(",");
            String[] dwyf = shareBean.getDwyf().split(",");
            String[] cgs = shareBean.getCgs1().split(",");
            String[] rys = shareBean.getRys1().split(",");
            String[] ttc = shareBean.getTtc1().split(",");
            String[] dfzc = shareBean.getDfzc1().split(",");
            String[] dszc = shareBean.getDszc1().split(",");
            String[] qxzc = shareBean.getQxzc1().split(",");
            String[] qtzc = shareBean.getQtzc1().split(",");
            String[] ztz = shareBean.getZtz1().split(",");
            String[] bd = shareBean.getBd().split(",");
            String[] xmdj = shareBean.getXmdj().split(",");
            String[] jhxdwh = shareBean.getJhxdwh().split(",");

            String[] nf = shareBean.getNf().split(",");
            String[] tbsj = shareBean.getTbsj().split(",");



            List<XmZjdw> save = new ArrayList<XmZjdw>();
            List<XmZjdw> update = new ArrayList<XmZjdw>();
            for (int i = 0; i < gydwdm.length; i++) {
                XmZjdw xm = new XmZjdw();
                xm.setGydwdm(gydwdm[i]);
                xm.setGydw(gydw[i]);
                xm.setParent(parent[i]);
                xm.setDwyf(dwyf[i]);
                if ("".equals(ztz[i]) || Double.parseDouble(ztz[i]) == 0d) {
                    continue;
                }
                xm.setCgs(Double.parseDouble("".equals(cgs[i]) ? "0" : cgs[i]));
                xm.setRys(Double.parseDouble("".equals(rys[i]) ? "0" : rys[i]));
                xm.setTtc(Double.parseDouble("".equals(ttc[i]) ? "0" : ttc[i]));
                xm.setDfzc(Double.parseDouble("".equals(dfzc[i]) ? "0" : dfzc[i]));
                xm.setDszc(Double.parseDouble("".equals(dszc[i]) ? "0" : dszc[i]));
                xm.setQxzc(Double.parseDouble("".equals(qxzc[i]) ? "0" : qxzc[i]));
                xm.setQtzc(Double.parseDouble("".equals(qtzc[i]) ? "0" : qtzc[i]));
                xm.setZtz(Double.parseDouble("".equals(ztz[i]) ? "0" : ztz[i]));
                xm.setBd(bd[i]);
                xm.setXmdj(xmdj[i]);
                xm.setJhxdwh(jhxdwh[i]);
                if("00".equals(gydwdm[i].substring(gydwdm[i].length()-2))){
                    xm.setXmbm("share"+nf[i]+gydwdm[i]+jhxdwh[i]);
                }else{
                    xm.setXmbm("share"+nf[i]+gydwdm[i]+jhxdwh[i]);
                }
                xm.setNf(nf[i]);
                xm.setTbsj(tbsj[i]);

                ShareBean shareBean = shareServer.queryshareFundByXmbm(xm);
                if (shareBean == null) {
                    int num = shareServer.insertXmjbxxShareFund(xm);
                }

                save.add(xm);

//                if (shareServer.queryShqxByOne(xm) == null) {
//                    save.add(xm);
//                } else {
//                    update.add(xm);
//                }
            }
            int a = 0;
            if (save.size() > 0) {
                a = shareServer.insertShqx(save);
            }
            if (update.size() > 0) {
                a = shareServer.updateShqx(update);
            }
            ResponseUtils.write(getresponse(), (a>0)+"");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getJhxdByWh() {
        try {
            ShareBean list =shareServer.getdwByWhbj(shareBean);
            JsonUtils.write(list, getresponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void queryZjByGydwdm() {
        try {
            ShareBean result = new ShareBean();

            shareBean.setXzqh(shareBean.getGydwdm().substring(5, 9));

            ShareBean bean = shareServer.getJhxdZjById(shareBean);

            ShareBean bean1 = shareServer.getzjdwById(shareBean);

            if (bean1 != null) {
                result.setZtz(String.valueOf(Integer.parseInt(bean.getZtz()) - Integer.parseInt(bean1.getZtz())));
            } else {
                result.setZtz(bean.getZtz());
            }
            JsonUtils.write(result, getresponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void queryChildGydw() {
        try {
            List<ShareBean> list = shareServer.queryChildGydw(shareBean);
            JsonUtils.write(list, getresponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void queryXmlistshqx(){
        shareBean.setGydw(MyUtil.getQueryTJ(shareBean.getGydw(), "t.gydwdm"));
        shareBean.setNf(MyUtil.getQueryTJ(shareBean.getNf(), "substr(dwyf,1,4)"));
        List<XmZjdw> list=shareServer.queryXmlistshqx(shareBean);
        int count=shareServer.queryXmlistshqxCount(shareBean);
        EasyUIPage<XmZjdw> e=new EasyUIPage<XmZjdw>();
        e.setRows(list);
        e.setTotal(count);
        try {
            JsonUtils.write(e, getresponse().getWriter());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void queryzjxdlist(){
        if("0".equals(shareBean.getSffy())){
            shareBean.setPage(1);
            shareBean.setRows(500);
        }
        List<XmZjdw> list=shareServer.queryzjxdlist(shareBean);
        int count=shareServer.queryzjxdlistCount(shareBean);
        EasyUIPage<XmZjdw> e=new EasyUIPage<XmZjdw>();
        e.setRows(list);
        e.setTotal(count);
        try {
            JsonUtils.write(e, getresponse().getWriter());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void getxmInfo() {
        FundBean results = shareServer.getxmInfo(shareBean);
        try {
            JsonUtils.write(results, getresponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void delSharefundXm() {
        ResultBean resultBean = new ResultBean();
        try {
            shareBean.setXzqhdm(shareBean.getXzqhdm().replaceAll("(00)$", ""));
            int count = shareServer.queryZjdwCountByXmbm(shareBean);
            if (count > 0) {
                resultBean.setCode(400);
                resultBean.setMsg("此项目已分配到位资金，不能删除！");
                resultBean.setSuccess(true);
                JsonUtils.write(resultBean, getresponse().getWriter());
                return;
            }
            boolean bl = shareServer.delSharefundXm(shareBean);
            if (bl) {
                resultBean.setCode(200);
                resultBean.setMsg("删除成功！");
                resultBean.setSuccess(true);
            } else {
                resultBean.setCode(400);
                resultBean.setMsg("删除失败！");
                resultBean.setSuccess(false);
            }
            JsonUtils.write(resultBean, getresponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addSharefundData() {
        ResultBean resultBean = new ResultBean();
        try {
            int count = shareServer.queryShareFundByXzqh(shareBean);
            if (count > 0) {
                resultBean.setCode(400);
                resultBean.setMsg("本年度已添加过，不能重复添加！");
                JsonUtils.write(resultBean, getresponse().getWriter());
                return;
            }
            boolean bl = shareServer.addSharefundData(shareBean);
            if (bl) {
                resultBean.setCode(200);
                resultBean.setMsg("添加成功");
            } else {
                resultBean.setCode(400);
                resultBean.setMsg("添加失败");
            }
            JsonUtils.write(resultBean, getresponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void importSharefundData() throws IOException {
        String fileType=fileuploadFileName.substring(fileuploadFileName.length()-3, fileuploadFileName.length());
        System.out.println("fileType = " + fileType);
        HttpServletResponse response = getresponse();
        try {
            if(!"xls".equals(fileType)){
                response.getWriter().print(fileuploadFileName+"不是系统导出的excel模版文件");
                return;
            }
            response.setCharacterEncoding("utf-8");
            FileInputStream fs = new FileInputStream(this.fileupload);
            List<Map>[] dataMapArray;
            dataMapArray = ExcelReader.readExcelContent(0,8,fs,Object.class);
            System.out.println(dataMapArray);
            List<Map> data = ExcelReader.removeBlankRow(dataMapArray[0]);
            System.out.println(data);
            if (data.size() >= 1) {
                if (data.get(0).get("0").equals("行政区划")
                        && data.get(0).get("1").equals("行政区划编码")
                   && data.get(0).get("2").equals("项目年份")
                   && data.get(0).get("3").equals("计划下达文号")
                   && data.get(0).get("4").equals("车购税")
                   && data.get(0).get("5").equals("省投资")
                   && data.get(0).get("6").equals("厅统筹")
                   && data.get(0).get("7").equals("地方自筹")) {
                    data.remove(0);
                } else {
                    response.getWriter().print(fileuploadFileName+"数据有误");
                    return;
                }
            } else {
                response.getWriter().print(fileuploadFileName+"数据有误");
                return;
            }
            List<Map> results = new ArrayList<Map>(10);
            for (Map map : data) {
                // todo 行政区划校验
                if (map.get("0") == null || map.get("0") == "") {
                    response.getWriter().print("行政区划不能为空！");
                    return;
                }
                if ("南昌市,景德镇市,萍乡市,九江市,新余市,鹰潭市,赣州市,吉安市,宜春市,抚州市,上饶市"
                        .indexOf(map.get("0").toString()) < 0) {
                    response.getWriter().print("行政区划与模板中不符！");
                    return;
                }
                if (map.get("1") == null || map.get("1") == "") {
                    response.getWriter().print("行政区划编码不能为空！");
                    return;
                }
                if ("360100,360200,360300,360400,360500,360600,360700,360800,360900,361000,361100"
                        .indexOf(map.get("1").toString()) < 0) {
                    response.getWriter().print("行政区划编码与模板不符！");
                    return;
                }
                if (map.get("2") == null || map.get("2") == "") {
                    response.getWriter().print("项目年份不能为空！");
                    return;
                }
                if (!map.get("2").toString().matches("\\d{4}")) {
                    response.getWriter().print("项目年份格式不正确！");
                    return;
                }
                if (map.get("3") == null || map.get("3") == "") {
                    response.getWriter().print("计划下达文号不能为空！");
                    return;
                }
                if (map.get("4") != null && map.get("4") != "") {
                    if (!map.get("4").toString().matches("\\d+(\\.)?\\d*")) {
                        response.getWriter().print("车购税数据格式不对！");
                        return;
                    }
                }
                if (map.get("5") != null && map.get("5") != "") {
                    if (!map.get("5").toString().matches("\\d+(\\.)?\\d*")) {
                        response.getWriter().print("省投资数据格式不对！");
                        return;
                    }
                }
                if (map.get("6") != null && map.get("6") != "") {
                    if (!map.get("6").toString().matches("\\d+(\\.)?\\d*")) {
                        response.getWriter().print("厅统筹数据格式不对！");
                        return;
                    }
                }
                if (map.get("7") != null && map.get("7") != "") {
                    if (!map.get("7").toString().matches("\\d+(\\.)?\\d*")) {
                        response.getWriter().print("地方自筹数据格式不对！");
                        return;
                    }
                }
                ShareBean bean = new ShareBean();
                bean.setXzqhdm(map.get("1").toString());
                bean.setXmnf(map.get("2").toString());
                bean.setJhxdwh(map.get("3").toString());
                int count = shareServer.queryShareFundByXzqh(bean);
                if (count > 0) {
                    continue;
                }
                String cgs = map.get("4") == null || map.get("4") == "" ? "0" : map.get("4").toString();
                String stz = map.get("5") == null || map.get("5") == "" ? "0" : map.get("5").toString();
                String ttc = map.get("6") == null || map.get("6") == "" ? "0" : map.get("6").toString();
                String dfzc = map.get("7") == null || map.get("7") == "" ? "0" : map.get("7").toString();

                if ("0".equals(cgs)
                        && "0".equals(stz)
                        && "0".equals(ttc)
                        && "0".equals(dfzc)) {
                    continue;
                }

                List<ShareBean> dwList = shareServer.queryDepartment(bean);
                String id = UUID.randomUUID().toString().replaceAll("-", "");
                for (ShareBean shareBean1 : dwList) {
                    String gydwdm = shareBean1.getGydwdm();
                    Map<String, Object> resultMap = new HashMap<String, Object>();
                    resultMap.put("id", id);
                    resultMap.put("xzqh", map.get("0"));
                    resultMap.put("xzqhdm", map.get("1"));
                    resultMap.put("gydwdm", gydwdm);
                    resultMap.put("gydw", shareBean1.getGydw());
                    resultMap.put("xmnf", map.get("2"));
                    resultMap.put("jhxdwh", map.get("3"));
                    resultMap.put("xmbm", "share"+map.get("2").toString()+gydwdm+map.get("3"));
                    resultMap.put("xmdj", gydwdm.startsWith("1") ? "农村" : "国省道");
                    resultMap.put("xmmc", map.get("2").toString()+shareBean1.getGydw()+map.get("3"));
                    resultMap.put("btzzj", cgs);
                    resultMap.put("stz", stz);
                    resultMap.put("ttc", ttc);
                    resultMap.put("dfzc", dfzc);
                    resultMap.put("ztz", Float.parseFloat(cgs)+Float.parseFloat(stz)+Float.parseFloat(ttc)+Float.parseFloat(dfzc));
                    results.add(resultMap);
                }
            }

            if (results.size() == 0) {
                response.getWriter().print("导入计划都已存在，请重复添加导入！");
                return;
            }
            boolean b = shareServer.importSharefund(results);
            if(b) {
                response.getWriter().print(fileuploadFileName+"导入成功");
            } else {
                ResponseUtils.write(getresponse(),  fileuploadFileName+"导入失败");
            }
        } catch (Exception e) {
            response.getWriter().print(fileuploadFileName+"数据有误");
            e.printStackTrace();
            return;
        }
    }

    public void exportmb() {
        try {
            ExcelTitleCell[] title = null;
            title = new ExcelTitleCell[8];
            title[0] = new ExcelTitleCell("行政区划", false,
                    new ExcelCoordinate(0, (short) 0), null, 15,true);
            title[1] = new ExcelTitleCell("行政区划编码", false,
                    new ExcelCoordinate(0, (short) 1), null, 15,true);
            title[2] = new ExcelTitleCell("项目年份", false,
                    new ExcelCoordinate(0, (short) 2), null, 15,true);
            title[3] = new ExcelTitleCell("计划下达文号", false,
                    new ExcelCoordinate(0, (short) 3), null, 15,true);
            title[4] = new ExcelTitleCell("车购税", false,
                    new ExcelCoordinate(0, (short) 4), null, 15,true);
            title[5] = new ExcelTitleCell("省投资", false,
                    new ExcelCoordinate(0, (short) 5), null, 15,true);
            title[6] = new ExcelTitleCell("厅统筹", false,
                    new ExcelCoordinate(0, (short) 6), null, 15,true);
            title[7] = new ExcelTitleCell("地方自筹", false,
                    new ExcelCoordinate(0, (short) 7), null, 15,true);
            Map<String, String> attribute = new HashMap<String, String>();
            attribute.put("0", "xzqh"); //行政区划
            attribute.put("1", "xzqhdm"); //行政区划模板
            attribute.put("2", "xmnf"); //项目年份
            attribute.put("3", "jhxdwh"); //计划下达文号
            attribute.put("4", "btzzj"); //车购税
            attribute.put("5", "stz"); //省投资
            attribute.put("6", "ttc"); //厅统筹
            attribute.put("7", "dfzc"); //地方自筹
            List<Object> excelData = new ArrayList<Object>();
            String titleName = "分成资金计划模版";
            String fileName = "分成资金计划模版";
            List<ShareBean> xzqhList = shareServer.queryMarketXzqh(shareBean);
            excelData.addAll(xzqhList);
            ExcelEntity excel = new ExcelEntity(titleName, title, attribute,excelData);
            ExcelExportUtil.excelWritelock(excel, fileName, getresponse());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
